<?php
error_reporting(E_ERROR);
class Admini_VisitingController extends Uuch_ManageController{
    
    public function init() {
        parent::init();
        $this->appendCss('/admins/css/yundan.css');
        $this->appendCss('/admins/css/common.css');
        $this->appendScript('/admins/js/jquery/jquery-1.7.2.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');
        $this->view->type="visiting";
        $this->setTitle("上门取件管理");
        $this->view->countbillout1 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Processing,null);
        $this->view->countbillout2 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Confrimed,null);
        $this->view->countbillout3 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_InformDelivery,null);
        $this->view->countbillout10 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Delivery,null);
        $this->view->countbillout11 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_InStore,null,0);
        $this->view->countbillout12 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_InStore,null,1);
        $this->view->countbillout13 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Pack,null);
        $this->view->countbillout14 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Inspections,null);
        $this->view->countbillout15 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_ArrearsFee,null);
        $this->view->countbillout17 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Payfreight,null);
        $this->view->countbillout18 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Payingmoney,null);
        $this->view->countbillout22 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Lose,null);
        $this->view->countbillout24 = Application_Model_VisitingServer::getCountByInteriorTime(null,null,null,1);
        $this->view->countbillout30 = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_Launch,null);
        $this->view->countbillout99 = Application_Model_VisitingServer::getCountByInteriorTime(null,1);
        $visitingAll = Application_Model_VisitingServer::getProblemVisting();
        //问题待回复和已回复
        $vid=array();
        $pid=array();
        foreach($visitingAll as $list){
            $proway=Application_Model_ProblemWay::getByTypeWayId($list->id,Application_Model_ProblemWay::Type_Visiting);
            if($proway){
                if($proway->status==1){
                    $vid[]=$proway->wayId;
                }elseif($proway->status==2){
                    $pid[]=$proway->wayId;
                }
            }
        }
        $this->view->countbillout25=count($vid);
        $this->view->countbillout26=count($pid);
    }    
       
    public function indexAction(){
        $pagesize = $this->getSafeParam('pagesize');
        if (!$pagesize) {
            $pagesize = 10;
        }
        $pageindex = $this->getSafeParam('start');
        if (!$pageindex) {
            $pageindex = 0;
        }
        $quick= $this->getSafeParam('quick');
        $timescope = $this->getSafeParam('timescope');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $cityId = $this->getSafeParam("cityId");
        $townId = $this->getSafeParam("townId");
        $startweight = $this->getSafeParam("startweight");
        $endweight = $this->getSafeParam("endweight");
        $startvolume = $this->getSafeParam("startvolume");
        $endvolume = $this->getSafeParam("endvolume");
        $startmoney = $this->getSafeParam("startmoney");
        $endmoney = $this->getSafeParam("endmoney");
        $isWay = $this->getSafeParam("isWay");
        $interiorId = $this->getSafeParam("interiorId");
        $day = $this->getSafeParam("day");
        $stus = $this->getSafeParam("stus");
        $isDel = $this->getSafeParam("isdel");
        $topay = $this->getSafeParam("topay");
        $problem = $this->getSafeParam("problem");
        $pstatus = $this->getSafeParam("pstatus");
        $interior = "";
        if($stus !== ""){
            $this->view->stype = $stus;
            $interior = $stus;
            if($stus == Application_Model_VisitingServer::Interior_InStore){
                if($isWay == 1){
                    $this->view->stype = 106;
                }
            }
        }else{
            $this->view->stype = 100;
        }
        if($day == 1){
            $this->view->stype = 99;
        }
        if($isDel == 1){
            $this->view->stype = 88;
        }
        if($topay == 1){
            $this->view->stype = 105;
        }
        if($problem == 1){
            $this->view->stype = 24;
        }
        $strart = date("m") % 3 == 0 ? date("m") / 3 : ((int) (date("m") / 3) + 1);
        if ($timescope != null) {
            switch ($timescope) {
                case 'lastweek':
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 7 - 7, date("Y")));
                    break;
                case "week":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 7, date("Y")));
                    break;
                case "month":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("t"), date("Y")));
                    break;
                case "lastmonth":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, cal_days_in_month(CAL_GREGORIAN, date("m") - 1, date("Y")), date("Y")));
                    break;
                case "quarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 + 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, $strart * 3, cal_days_in_month(CAL_GREGORIAN, $strart * 3, date("Y")), date("Y")));
                    break;
                case "lastquarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 - 2, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3, cal_days_in_month(CAL_GREGORIAN, ($strart - 1) * 3, date("Y")), date("Y")));
                    break;
                case "year":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, 12, cal_days_in_month(CAL_GREGORIAN, 12, date("Y")), date("Y")));
                    break;
                case "lastyear":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y") - 1));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, 12, cal_days_in_month(CAL_GREGORIAN, 12, date("Y") - 1), date("Y") - 1));
                    break;
                case "day7":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 6, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "day30":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 30, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                default :
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
            }
        } else {
            if ($starttime == null && $endtime == "") {
//                $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
//                $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
            }
        }
        $visitingSearch = new Application_Model_Filter_VisitingSearch();
        $visitingSearch->quick = $quick;
        if($day !== ""){
            $visitingSearch->starttime = date("Y-m-d");
            $visitingSearch->endtime = date("Y-m-d");
        }else{
            $visitingSearch->starttime = $starttime;
            $visitingSearch->endtime = $endtime;
        }
        $visitingSearch->cityId = $cityId;
        $visitingSearch->townId = $townId;
        $visitingSearch->startWeight = $startweight;
        $visitingSearch->endWeight = $endweight;
        $visitingSearch->startVolume = $startvolume;
        $visitingSearch->endVolume = $endvolume;
        $visitingSearch->startMoney = $startmoney;
        $visitingSearch->endMoney = $endmoney;
        $visitingSearch->isWay = $isWay;
        $visitingSearch->topay = $topay;
        if($interior !== ""){
            $visitingSearch->interiorId = $interior;
        }else{
            $visitingSearch->interiorId = $interiorId;
        }        
        $visitingSearch->isDel = $isDel;
        $visitingSearch->problem = $problem;
        $visitingSearch->pstatus = $pstatus;
        $visitingAll = Application_Model_VisitingServer::getVisitingAll($visitingSearch,$pagesize,$pageindex);
        $uid=array();
        foreach($visitingAll['list'] as $item){
            $paypalBill=Application_Model_PayBill::getCardBill($item->userId,$item->id,Application_Model_PayBill::TYPE_Visiting);
            if($paypalBill){
                $datepid=strtotime($paypalBill[0]->dateCreated)+60*60*24;
                if($datepid > time()){
                    $uid[]=$item->userId;
                }
            }
        }
        $this->view->paypalBill=$uid;
        
        $defaultCityId = Application_Model_city::ParentDefaultCity;
        $defaultTownId = $cityId?$cityId:Application_Model_city::ParentDefaultTown;
        $this->view->cityAll = Application_Model_city::GetByParentId($defaultCityId, null);
        $this->view->townAll = Application_Model_city::GetByParentId($defaultTownId, null);
        $this->view->visitingAll = $visitingAll;

        //问题待回复和已回复
        $vid=array();
        if($problem && $pstatus){
            foreach($visitingAll["list"] as $list){
                $proway=Application_Model_ProblemWay::getByTypeWayId($list->id,Application_Model_ProblemWay::Type_Visiting);
                if($pstatus==$proway->status){
                    $vid[]=$proway->wayId;
                }
            }
            if($vid){
                $id=implode(',',$vid);
            }else{
                $id=0;
            }
            if ($pstatus==1) {
                $this->view->stype = 25;
            }
            elseif ($pstatus==2) {
                $this->view->stype = 26;
            }
            
            $visitingAll = Application_Model_VisitingServer::getproblemVisitingAll($visitingSearch,$pagesize,$pageindex,$id);
            $this->view->visitingList = $visitingAll["list"];
        }else{
            $this->view->visitingList = $visitingAll["list"];
        }
        $this->view->interiorAll = Application_Model_VisitingServer::getInteriorAll();
        
        $this->view->quick = $quick;
        $this->view->timescope = $timescope;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->pagesize = $pagesize;
        $this->view->cityId = $cityId;
        $this->view->townId = $townId;
        $this->view->startweight = $startweight;
        $this->view->endweight = $endweight;
        $this->view->startvolume = $startvolume;
        $this->view->endvolume = $endvolume;
        $this->view->startmoney = $startmoney;
        $this->view->endmoney = $endmoney;
        $this->view->isWay = $isWay;
        $this->view->interiorId = $interiorId;
    }
    /**
     * 获取补交的金额及付款地址
     */
    public function cultfeeAction()
    {   
        $visitingId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($visitingId);
        $weight = $this->getSafeParam('weight');
        $volume = $this->getSafeParam("volume");
        $weight = (int)($weight*1000);
        $volume = (int)($volume*1000);
        $way = Application_Model_wayBillItem::load($visitingItem->WayId);
        $productWeight = $weight;
        if($way->ExpressBy->IsVolume == 1){
            $productWeight = $volume>$weight?$volume:$weight;
        }
//        var_dump($productWeight);exit;
        $prices = Application_Model_ExpressPrice::getPricesByCity($way->state);
        $SortKey = 0;
        foreach ($prices as $item) {
            if($item->expressId == $way->shipType)
            {
                $SortKey = $item->getMoneyByweight($productWeight);
                break;
            }
        }
        Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "获取补交的金额", $visitingItem->userId);
        $money = $SortKey+$way->getFeeByType(Application_Model_FeeType::VacuumSeviceFee)+$way->getFeeByType(Application_Model_FeeType::WoodenFee)+$way->getFeeByType(Application_Model_FeeType::RatePremiumFee)+$way->getFeeByType(Application_Model_FeeType::RemoteFee)+$visitingItem->ActualCnShipFee;        
        if($money>$visitingItem->advanceMoney){
            $this->json(array('type'=>1,'arrearsMoney'=>($money - $visitingItem->advanceMoney),'shipFee'=>$SortKey,'money'=>$money)); 
        }else{            
            $this->json(array('type'=>0,'shipFee'=>$SortKey,'money'=>$money));
        }
    }
    /**
     * 详情页
     */
    public function vsdetailAction()
    {
        $vsId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($vsId); 

        $Visiting=Application_Model_PaypalRisk::getVisiting($visitingItem->userId);
        $this->view->Visiting = $Visiting;
        $Visitingbill=Application_Model_PayBill::getCardBill($visitingItem->userId,$visitingItem->id,Application_Model_PayBill::TYPE_Visiting);
        if($Visitingbill){
            $datepid=strtotime($Visitingbill[0]->dateCreated)+60*60*24;
            if($datepid > time()){
                $Visitingbill=$Visitingbill;
            }else{
                $Visitingbill=FALSE;
            }
        }
        $this->view->visitingpay=$Visitingbill;

        $payLink = Application_Model_RepayLink::getByRelationIdType($visitingItem->Id, Application_Model_PayBill::TYPE_Visiting);
        $jiesuanLink = Application_Model_RepayLink::getByRelationId($vsId, Application_Model_PayBill::TYPE_Visiting);
        $packWeight = Application_Model_WayWeight::getWeightByType($visitingItem->wayId,Application_Model_WeightType::Visiting_PackWeight);
        $packVolume = Application_Model_WayWeight::getWeightByType($visitingItem->wayId,Application_Model_WeightType::Visiting_PackVolume);
        $this->view->packWeight = $packWeight?$packWeight->weight:0;
        $this->view->packVolume = $packVolume?$packVolume->weight:0;
        $wayBillItem = Application_Model_wayBillItem::load($visitingItem->wayId);
        $this->view->wayBillItem = $wayBillItem;
        $this->view->payLink = $payLink;
        $this->view->jiesuanLink = $jiesuanLink;
        $this->view->shipFee = $wayBillItem->shipFee?$wayBillItem->shipFee:"0.00";
        $this->view->vsDetail = $visitingItem;
        $remarkModel = Application_Model_Remark::getObjectSimpleRemark($visitingItem->id,Application_Model_Remark::OBJECT_VISITING_TYPE);
        $this->view->modelRemark = $remarkModel;
        $store = new Application_Model_StoreItem();
        $this->view->cnShipFree = $store->getActCnShipFee($visitingItem->inlandLogistics);
        $this->view->storedetail = $visitingItem->getItems();
        $this->view->express = Application_Model_Express::load($visitingItem->inlandShipType); 
        $this->view->issuedetail = Application_Model_problem::byissue($vsId, Application_Model_problem::TYPE_VISITING);
        $this->view->problemWay = Application_Model_ProblemWay::getByTypeWayId($vsId, Application_Model_ProblemWay::Type_Visiting);
        $this->view->scheduledetail = Application_Model_ProblemSchedule::getTypeWayIdBySchedule($vsId, Application_Model_ProblemSchedule::Type_Visiting);
        $this->view->packSize = Application_Model_WayLog::getPackSize($vsId, Application_Model_WayLog::Type_Visiting,Application_Model_WayLog::Type_BillVolume);
    }
    /**
     * 受理
     */
    public function hearAction()
    {
        $vsId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->status == Application_Model_VisitingServer::STATUS_Processing && $visitingItem->interior == Application_Model_VisitingServer::Interior_Processing)
        {
            $visitingItem->status = Application_Model_VisitingServer::STATUS_Confrimed;
            $visitingItem->interior = Application_Model_VisitingServer::Interior_Confrimed;
            $visitingItem->save();
            $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Confrimed);
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件受理", $visitingItem->userId);
            $this->json(1);
        }else{
            $this->json(0);
        }
    }
    /**
     * 通知顺丰取件
     */
    public function informsfAction()
    {
        $vsId = $this->getSafeParam("id");
        $sfNo = $this->getSafeParam("sfNo");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->status == Application_Model_VisitingServer::STATUS_Confrimed && $visitingItem->interior == Application_Model_VisitingServer::Interior_Confrimed){
            if($sfNo == ""){
                $this->json(2);   //顺丰单号不能为空
            }else{
                $visitingItem->sfNo = $sfNo;
                $visitingItem->interior = Application_Model_VisitingServer::Interior_InformDelivery;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_InformDelivery);
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件通知顺丰取件", $visitingItem->userId);
                $this->json(1);    //成功
            }
        }else{
            $this->json(0);     //失败
        }
    }
    /**
     * 已取件
     */
    public function deliveryAction()
    {
        $vsId = $this->getSafeParam("id");
        $inlandLogistics = $this->getSafeParam("inlandLogistics");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->status == Application_Model_VisitingServer::STATUS_Confrimed && $visitingItem->interior == Application_Model_VisitingServer::Interior_InformDelivery){
            $visitingItem->status = Application_Model_VisitingServer::STATUS_Delivery;
            $visitingItem->interior = Application_Model_VisitingServer::Interior_Delivery;
            $visitingItem->inlandLogistics = $inlandLogistics;
            $visitingItem->save();
            $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Delivery);
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件顺丰已取件", $visitingItem->userId);
            $this->json(1);  //成功
        }else{
            $this->json(0);     //失败
        }
    }
   
    /**
     * 打包
     */
    public function packvisitingAction()
    {
        $visitingId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($visitingId);
        if($visitingItem && $visitingItem->status == Application_Model_VisitingServer::STATUS_InStore && $visitingItem->interior == Application_Model_VisitingServer::Interior_InStore){
            $weight = $this->getSafeParam("weight")?$this->getSafeParam("weight"):0;
            $volume = $this->getSafeParam("volume")?$this->getSafeParam("volume"):0;
            $length = $this->getSafeParam("length");
            $width = $this->getSafeParam("width");
            $height = $this->getSafeParam("height");
            $shipFee = $this->getSafeParam("shipFee");
            $description = $length."*".$width."*".$height;
            $arrearsMoney = $this->getSafeParam("arrearsMoney");
            $result = $visitingItem->PackVisiting($weight,$volume,$description,$shipFee);
            if($result){
                if($visitingItem->advanceMoney >= $shipFee){
                    $visitingItem->isArrears = 0;  //不需要补交运费
                }else {
                    $visitingItem->arrearsMoney = $arrearsMoney;
                    $visitingItem->isArrears = 1;  //需要补交运费
                }
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Pack);
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件顺丰已打包", $visitingItem->userId);
                $this->json(1);        //成功
            }else{
                $this->json(0);       //失败
            }
        }else{
            $this->json(2);          //只有入库状态下才能打包（出错）
        }
    }
    
    /**
     * 审单
     */
    public function inspectionsAction(){
        error_reporting(NULL);
        ini_set('display_errors','Off');
        $visitingId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($visitingId);
        if($visitingItem && $visitingItem->status == Application_Model_VisitingServer::STATUS_InStore && $visitingItem->interior == Application_Model_VisitingServer::Interior_Pack){
            $wayItem = Application_Model_wayBillItem::load($visitingItem->wayId);
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件已审单", $visitingItem->userId);
            if($visitingItem->isArrears == 1){                
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Inspections;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Inspections);
                if($wayItem != null){                     
                    $this->json(array('type'=>1));  //需要补交款
                }else{
                    $this->json(array('type'=>10));  //没有关联运单
                }
            } else {                
                $visitingItem->interior = Application_Model_VisitingServer::Interior_ArrearsFee;
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Launch;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Inspections);
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_ArrearsFee);
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Launch);  
                if($wayItem != null){
                    $wayItem->status = Application_Model_wayBillItem::STATUS_Processing;
                    $wayItem->interior = Application_Model_wayBillItem::Interior_Processing;
                    $wayItem->DatePaid = date('Y-m-d H:i:s');
                    foreach($wayItem->StoreItems as $item){
                         $item->state = Application_Model_StoreItem::STATUS_Sended;
                         $item->save();
                    }
                    $wayItem->save();
                    $this->json(array('type'=>2));    //不需要补交款
                }else{
                    $this->json(array('type'=>10));   //没有关联运单
                }
            }                        
        }else{
            $this->json(array('type'=>0));
        }
    }
    
    /*直发海外 客服手动扣款（补交款）并启动国际运单*/
    public function manualpaidAction(){
        $visitingId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($visitingId);
        $wayItem = Application_Model_wayBillItem::load($visitingItem->wayId);
        if($visitingItem->isArrears == 1){
            $visitingItem->Interior = Application_Model_VisitingServer::Interior_ArrearsFee;
            $visitingItem->Interior = Application_Model_VisitingServer::Interior_Launch;
            $visitingItem->Status = Application_Model_VisitingServer::STATUS_Launch;
            $visitingItem->save();
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件客服手动扣补交款，启动国际运单", $visitingItem->userId);
            $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_ArrearsFee);
            $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Launch);  
            if($wayItem != null){
                $wayItem->status = Application_Model_wayBillItem::STATUS_Processing;
                $wayItem->interior = Application_Model_wayBillItem::Interior_Processing;
                $wayItem->DatePaid = date('Y-m-d H:i:s');
                foreach($wayItem->StoreItems as $item){
                     $item->state = Application_Model_StoreItem::STATUS_Sended;
                     $item->save();
                }
                $wayItem->save();
                $wayFee = Application_Model_WayFee::getByWayIdFeeType($visitingItem->WayId, Application_Model_FeeType::EstimateSum);
                $wayFee->Money = $wayItem->ShipFee;
                $wayFee->save();
                $this->json(array('type'=>2));    //成功启动国际运单
            }else{
                $this->json(array('type'=>10));   //没有关联运单
            }
        }
    }
    
    
    
    /*获取补交款链接*/
    public function getpaylinkAction(){
        error_reporting(NULL);
        ini_set('display_errors','Off');
        $id = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($id);        
        if($visitingItem->isArrears == 1){
            $res = Application_Model_VisitingServer::getPaylink($id);
            if($res){
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Payingmoney;
                $visitingItem->status = Application_Model_VisitingServer::STATUS_Payingmoney;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Payingmoney);
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件生成补交款链接", $visitingItem->userId);
            }
            $link = $res->getPayLink(Application_Model_PayBill::TYPE_REPAY_LINK);
            $this->json(array('type'=>1,'link'=>$link));  //需要补交款
        }else{
            $this->json(array('type'=>0));  //不需要补交款
        }
    }
    
    
    /**
     * 根据城市Id获取其下级市级
     */
    public function citysubtownAction()
    {
        $cityId = $this->getSafeParam("cityid");
        $townItem = Application_Model_city::GetByParentId($cityId, null);
        $this->json($townItem);
    }
    
    /**
     * 根据id修改前台状态
     */
    public function changestatusAction(){
        $id = $this->getSafeParam("id");
        $status = $this->getSafeParam("status");
        $opt = Application_Model_VisitingServer::load($id);
        if($opt){
            $opt->status = $status;
            $opt->save();
            Application_Model_Operate::addOperate(0, null, $opt->visitingNo, "上门取件客服修改前台状态为：".$opt->getStatusName(), $opt->userId);
            $this->json(1);
        }else{
            $this->json(0);    
        }
    } 
    
    /**
     * 根据id修改后台状态
     */
    public function changeinteriorAction(){
        $id = $this->getSafeParam("id");
        $interior = $this->getSafeParam("interior");
        $opt = Application_Model_VisitingServer::load($id);
        if($opt){
            $opt->interior = $interior;
            $opt->save();
            Application_Model_Operate::addOperate(0, null, $opt->visitingNo, "上门取件客服修改后台状态为：".$opt->getInteriorName(), $opt->userId);
            $opt->delLog();
            $this->json(1);
        }else{
            $this->json(0);    
        }
    }
    
    /**
     * 取消问题
     */
    public function cancelAction(){
        $id = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($id);
        $type = Application_Model_ProblemWay::Type_Visiting;
        $one = Application_Model_ProblemWay::getByTypeWayId($id,$type);
        if($one){
            $opt = Application_Model_ProblemWay::load($one->id);
            $opt->status = Application_Model_ProblemWay::Problem_Cancel;
            $opt->save();
            $visitingItem->addProblemSchedule("问题取消", null, null);
            $visitingItem->problem = Application_Model_VisitingServer::Problem_SolveProblem;
            $visitingItem->save();
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "问题上门取件设为正常", $visitingItem->userId);
            $this->json(1);
        }else{
            $this->json(0);
        }
    }
    
    /**
     * 启动国际运单
     */
    public function startwaybillAction(){
        $id = $this->getSafeParam("id");
        $opt = Application_Model_VisitingServer::load($id);
        if($opt && $opt->interior == Application_Model_VisitingServer::Interior_ArrearsFee){
            $opt->interior = Application_Model_VisitingServer::Interior_Launch;
            $opt->status = Application_Model_VisitingServer::STATUS_Launch;            
            $opt->save();
            $opt->addBillLog(Application_Model_VisitingServer::Interior_Launch);
            $this->json(1);
        }else{
            $this->json(0);
        }
    }
    
    /**
     * 记录问题
     */
     public function affirmvsproblemAction(){
        $vsId = $this->getSafeParam("id");
        $content = $this->getSafeParam("content");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->problem != Application_Model_VisitingServer::Problem_Cancel && $visitingItem->interior != Application_Model_VisitingServer::STATUS_Launch){
            if(htmlspecialchars($content) != ""){
                $visitingItem->addProblem(htmlspecialchars($content));
                $visitingItem->problem = Application_Model_VisitingServer::Problem_AppearProblem;
//                $visitingItem->interior = Application_Model_VisitingServer::Interior_DeliveryProblem;
                $visitingItem->save();
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件标注问题：".$content, $visitingItem->userId);
                $this->json(1);         //成功
            }else{
                $this->json(2);        //内容为空 
            }
        }else{
           $this->json(0);           //问题取消或者已发国际运单不能标问题
        }
    }
    
    /**
     * 标注问题处理进度
     */
    public function affirmscheduleAction() {
        $vsid = $this->getSafeParam("id");
        $schedule = $this->getSafeParam("schedule");
        $crdate = $this->getSafeParam("crdate");
        $visitingItem = Application_Model_VisitingServer::load($vsid);
        if ($visitingItem && $visitingItem->interior != Application_Model_VisitingServer::Interior_Cancel) {
            $visitingItem->addProblemSchedule($schedule, null, $crdate);
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "问题上门取件处理进度：".$schedule, $visitingItem->userId);
            $this->json(1);         //成功
        } else {
            $this->json(0);           //问题取消不能标注处理进度
        }
    }
     
    /**
     * 快件丢失
     */
    public function lostAction(){
        $vsId = $this->getSafeParam("id");
        $type = Application_Model_ProblemWay::Type_Visiting;
        $one = Application_Model_ProblemWay::getByTypeWayId($vsId,$type);
        if($one->status != Application_Model_ProblemWay::Problem_Cancel && $one->status != ""){
            $visitingItem = Application_Model_VisitingServer::load($vsId);
            if($visitingItem){
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Lose;
                $visitingItem->status = Application_Model_VisitingServer::STATUS_Lose;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Lose);
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "标记上门取件包裹丢失", $visitingItem->userId);
                $this->json(1);         //标注快件丢失  

            }else{
                $this->json(0);       //无该上门取件记录
            }
        }else{
            $this->json(2);         //没有标记问题的包裹，不能标注快件丢失
        }
    }
    
    /*付款链接列表*/
    public function paymentAction(){
        $quick = $this->getSafeParam("quick");
        $status = $this->getSafeParam("status");
        $count = $this->getSafeParam("count");
        if(!$count){ $count=10; }
        $start = $this->getSafeParam("start");
        if(!$start){ $start=0; }
        if($status == 1){
            $this->view->stype = 102;
        }else if($status == 0 && $status != ""){
            $this->view->stype = 103;
        }else{
            $this->view->stype = 104;
        }
        $timescope = $this->getSafeParam('timescope');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $strart = date("m")%3==0?date("m")/3:((int)(date("m")/3)+1);
        if($timescope != null){
            switch ($timescope) {
                case "yesterday":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
                    break;
                case "day3":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-3,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
                    break;
                case 'lastweek':
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-date("w")+1-7,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-date("w")+7-7,date("Y")));
                    break;
                case "week":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-date("w")+7,date("Y")));
                    break;
                case "month":
                    $starttime =  date("Y-m-d",mktime(0,0,0,date("m"),1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("t"),date("Y")));
                    break;
                case "lastmonth":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m")-1,1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m")-1,cal_days_in_month(CAL_GREGORIAN, date("m")-1, date("Y")),date("Y")));
                    break;
                case "quarter":
                    $starttime = date("Y-m-d",mktime(0,0,0,($strart-1)*3+1,1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,$strart*3,cal_days_in_month(CAL_GREGORIAN, $strart*3, date("Y")),date("Y")));
                    break;
                case "lastquarter":
                    $starttime = date("Y-m-d",mktime(0,0,0,($strart-1)*3-2,1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,($strart-1)*3,cal_days_in_month(CAL_GREGORIAN, ($strart-1)*3, date("Y")),date("Y")));
                    break;
                case "year":
                    $starttime = date("Y-m-d",mktime(0,0,0,1,1,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,12,cal_days_in_month(CAL_GREGORIAN, 12, date("Y")),date("Y")));
                    break;
                case "lastyear":
                    $starttime = date("Y-m-d",mktime(0,0,0,1,1,date("Y")-1));
                    $endtime = date("Y-m-d",mktime(0,0,0,12,cal_days_in_month(CAL_GREGORIAN, 12, date("Y")-1),date("Y")-1));
                    break;
                case "day7":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-6,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
                    break;
                case "day30":
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-30,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
                    break;
                default :
                    $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-90,date("Y")));
                    $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
                    break;
            }
        }else{
            if($starttime == null && $endtime == ""){
                $starttime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-1));
                $endtime = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
            }
        }
        $this->view->quick = $quick;
        $this->view->status = $status;
        $this->view->count = $count;
        $this->view->start = $start;
        $this->view->timescope = $timescope;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->paylink = Application_Model_RepayLink::getMyByFilter($quick,$status,$count,$start,$starttime,$endtime);
        $this->view->paylinkList = $this->view->paylink['list'];        
    }
    
    /*根据id获取付款链接描述*/
    public function paylinkcontentAction(){
        $id = $this->getSafeParam("id");
        $res = Application_Model_RepayLink::load($id);
        if($res){
            $this->json(array('type'=>1,'content'=>$res->description));
        }else{
            $this->json(array('type'=>0));
        }
    }
    
    /*取消上门取件服务*/
    public function cancelserviceAction(){
        $id = $this->getSafeParam("vsId");
        $refunds = $this->getSafeParam("refunds");
        $visitingItem = Application_Model_VisitingServer::load($id);
        if($visitingItem->interior != Application_Model_VisitingServer::Interior_Cancel && $visitingItem->Interior != Application_Model_VisitingServer::Interior_WaitPay){
            $res = Application_Model_User::editmoney($visitingItem->userId,$refunds,"上门取件(".$visitingItem->visitingNo.")取消退款","message","refund",$visitingItem->visitingNo);
            //如有使用优惠券,需要取消占用
            $coupons = Application_Model_Coupon::getByWayId($visitingItem->wayId);
            foreach ($coupons as $coupon) {
                $coupon->Relevance = null;
                $coupon->Status = Application_Model_Coupon::STATUS_OK;
                $coupon->save();
            }
            if($res == 5){
                $visitingItem->status = Application_Model_VisitingServer::STATUS_Cancel;
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Cancel;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Cancel);
                $wayBillItem = Application_Model_wayBillItem::load($visitingItem->WayId);
                $wayBillItem->Status = Application_Model_wayBillItem::STATUS_Cancel;
                $wayBillItem->Interior = Application_Model_wayBillItem::Interior_Cancel;
                $wayBillItem->save();
                Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "取消上门取件", $visitingItem->userId);
                $this->json(1);
            }else{
                $this->json(0);
            }
        }else{
            $this->json(2);
        }
    }
    
    /*上门取货（存入云仓库）结算*/
    public function jiesuanAction(){
        $vsId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->isWay != 1){
            $store = new Application_Model_StoreItem();
            $cnShipFree = $store->getActCnShipFee($visitingItem->inlandLogistics);
            $guaranteeFee = $visitingItem->guaranteeFee?$visitingItem->guaranteeFee:0;            
            $money = $cnShipFree - $guaranteeFee;
            if($money <= 0){
                if($money == -100){
                    $this->json(array('type'=>3));
                }else{
                    $res = Application_Model_User::editmoney($visitingItem->userId,-$money,"上门取件(".$visitingItem->visitingNo.")结算退款","message","jiesuan",$visitingItem->visitingNo);
                    if($res == 6){
                        $visitingItem->status = Application_Model_VisitingServer::STATUS_Complete;
                        $visitingItem->interior = Application_Model_VisitingServer::Interior_Complete;
                        $visitingItem->save();
                        $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Complete);
                        Application_Model_Operate::addOperate($money, null, $visitingItem->visitingNo, "上门取件（存入云仓库）结算退款", $visitingItem->userId);
                        foreach($visitingItem->StoreItems as $item){
                           $item->cnShipFee = 0;
                           $item->State = Application_Model_StoreItem::STATUS_InStored;
                           $item->save();
                        }                    
                        $this->json(array('type'=>1));
                        $money = abs($money);
                        $account = Application_Model_UserAccount::load($visitingItem->userId);
                        $afterMoney = $account->Money;
                        $beforeMoney = $afterMoney - $money;
                        $params = array('businessType'=>'gryftk','visitingNo' => $visitingItem->visitingNo,'beforeMoney'=>$beforeMoney,'afterMoney'=>$afterMoney,'account'=>$account,'trader'=>'account-number-dr');
                        $this->_addFinance($money, $params);
                        $params['beforeMoney'] = $params['afterMoney'];
                        $params['trader'] = 'backend-account-cr';
                        $this->_addFinance($money, $params);
                    }
                }
            }else{
                $payLink = Application_Model_RepayLink::createRepayLink("上门取件（".$visitingItem->visitingNo."）结算", "上门取件（".$visitingItem->visitingNo."）结算", Application_Model_PayBill::TYPE_Visiting, $visitingItem->id, $money, $visitingItem->userId);
                $payLink->save();
                $visitingItem->status = Application_Model_VisitingServer::STATUS_Payfreight;
                $visitingItem->interior = Application_Model_VisitingServer::Interior_Payfreight;
                $visitingItem->save();
                $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Payfreight);
                Application_Model_Operate::addOperate($money, null, $visitingItem->visitingNo, "上门取件（存入云仓库）结算补交", $visitingItem->userId);
                $link = "http://old.uuch.com/pay/paying/id/".$payLink->id."9";
                $this->json(array('type'=>0,'link'=>$link));  //上门取件结算链接
            }
        }else{
            $this->json(array('type'=>2));      //选择直发海外  不能结算
        }
    }
    
    /*上门取货（存入云仓库）客服手动扣款结算*/
    public function settlementAction(){
        $vsId = $this->getSafeParam("id");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if($visitingItem->isWay != 1){
            $visitingItem->status = Application_Model_VisitingServer::STATUS_Complete;
            $visitingItem->interior = Application_Model_VisitingServer::Interior_Complete;
            $visitingItem->save();
            $visitingItem->addBillLog(Application_Model_VisitingServer::Interior_Complete);
            Application_Model_Operate::addOperate(0, null, $visitingItem->visitingNo, "上门取件（存入云仓库）手工扣款结束", $visitingItem->userId);
            foreach($visitingItem->StoreItems as $item){
               $item->cnShipFee = 0;
               $item->State = Application_Model_StoreItem::STATUS_InStored;
               $item->save();
            }                    
            $this->json(array('type'=>1));
        }else{
            $this->json(array('type'=>0));
        }
    }
    
    
    
    /*根据id标记删除上门取件记录*/
    public function deletebyidAction(){
        $id = $this->getSafeParam("id");
        $visitItem = Application_Model_VisitingServer::load($id);
        if($visitItem){
            $visitItem->isDel = 1;
            $visitItem->save();
            Application_Model_Operate::addOperate(0, null, $visitItem->visitingNo, "上门取件标记删除", $visitItem->userId);
            $this->json(1);    //删除成功       
        }else{
            $this->json(0);      //删除失败
        }
    }
    
    public function remarkAction(){
        $id = $this->getSafeParam("id");
        $interNote = $this->getSafeParam("interiorNote");
        $visitItem = Application_Model_VisitingServer::load($id);
        if($visitItem){
//            $visitItem->interiorRemark = $interNote;
//            $visitItem->save();
            $remarkModel = Application_Model_Remark::getObjectSimpleRemark($visitItem->id,Application_Model_Remark::OBJECT_VISITING_TYPE);
            if(!$remarkModel){
                $remarkModel = new Application_Model_Remark();
            }
            $data = array(
                'remarkType' => Application_Model_Remark::REMARKTYPE_INTERIOR,
                'content' => $interNote,
                'operator' => Uuch_Util::getUserNikeName(),
                'objectId' => $visitItem->id,
                'objectType' => Application_Model_Remark::OBJECT_VISITING_TYPE,
                'createdAt' => date('Y-m-d H:i:s')
                    );
            $remarkModel->setData($data)->save();
            $this->json(1);
        }else{
            $this->json(0);
        }        
    }
    
    protected function _addFinance($money, $params) {
        
        $account = $params['account'];
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $user = Application_Model_User::load($account->id);
        $remark = isset($params['remark']) ? $params['remark'] : '';
        $data = array(
            'transaction_number' => '',
            'trader' => $params['trader'],
            'customer_id' => $account->id,
            'customer_name' => $user->nikename,
            'member' => 'admin',
            'amount' => $money,
            'currency' => 'CNY',
            'rate' => '1',
            'rate_amount' => '0',
            'period_start' => $params['beforeMoney'],
            'period_end' => $params['afterMoney'],
            'business_type' => $params['businessType'],
            'order_sn' => $params['visitingNo'],
            'remark' => $remark,
            'created_at' => date('Y-m-d H:i:s')
        );
        try {
            $api = new General($params['beforeMoney'], $account);
            $api->setFields($data);
            $api->addTransaction();
            $result = array('code' => 'success', 'message' => '');
        } catch (Exception $ex) {
            $result = array('code' => 'error', 'message' => $ex->getMessage());
        }
    }
    
}


